package com.carlinfo.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 文件的工具类
 */
public class IOUtil
{
	/**
	 * logger:接口 LogManger:类
	 */
	private Logger logger = LogManager.getLogger();

	/**
	 * 读取文件;字符文件;(字符流) 有缺点:如果把此工具类靠背给其他人使用;路径有问题;
	 */
	public String readFile(File souFile)
	{
		/* 结果 */
		StringBuffer sb = new StringBuffer();
		BufferedReader br = null;
		try
		{
			InputStream in = new FileInputStream(souFile);
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			logger.error("读取文件内容失败了;文件的路径:{}", souFile.getAbsolutePath(), e);
		} finally
		{
			try
			{
				if (br != null)
				{
					br.close();
					br = null;
				}
			} catch (IOException e)
			{
				logger.error("关闭失败了;文件的路径:{}", souFile.getAbsolutePath(), e);
			}
		}
		return sb.toString();
	}

	public String readFile(InputStream in)
	{
		/* 结果 */
		StringBuffer sb = new StringBuffer();
		BufferedReader br = null;
		try
		{
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");
			br = new BufferedReader(isr);
			String line = "";
			while ((line = br.readLine()) != null)
			{
				sb.append(line + "\r\n");
			}
		} catch (Exception e)
		{
			// e.printStackTrace();
			logger.error("读取文件内容失败了;", e);
		} finally
		{
			try
			{
				if (br != null)
				{
					br.close();
					br = null;
				}
			} catch (IOException e)
			{
				// e.printStackTrace();
				logger.error("关闭失败了;", e);
			}
		}

		return sb.toString();
	}

	public static void main(String[] args)
	{
		File file = new File("a.txt");
		System.out.println("====" + file.getAbsolutePath());
		System.out.println("==IOUtil.class==" + IOUtil.class);
		Class cla = IOUtil.class;
		System.out.println("==Resource==" + cla.getResource("/config.json"));
		/* 输入流 */
		InputStream in = cla.getResourceAsStream("/config.json");
		IOUtil ioUtil = new IOUtil();
		File souFile = new File("D:\\workspace\\userscenter\\src_config\\config.json");
		String fileStr = ioUtil.readFile(souFile);
		System.out.println("==基于路径==" + fileStr);
		InputStream is = IOUtil.class.getClassLoader().getClass().getResourceAsStream("/config.json");
		fileStr = ioUtil.readFile(is);
		System.out.println("==classpath==" + fileStr);
	}

}
